package com.webside.advertisement.controller;
 
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.webside.advertisement.model.AdReleaseEntity;
import com.webside.advertisement.model.AdvertisementEntity;
import com.webside.advertisement.service.AdPositionService;
import com.webside.advertisement.service.AdReleaseService;
import com.webside.advertisement.service.AdvertisementService;
import com.webside.base.basecontroller.BaseController;
import com.webside.dtgrid.model.Pager;
import com.webside.dtgrid.util.ExportUtils;
import com.webside.exception.AjaxException;
import com.webside.exception.ServiceException;
import com.webside.exception.SystemException;
import com.webside.series.model.SeriesEntity;
import com.webside.util.Common;
import com.webside.util.PageUtil;
 

@Controller
@Scope("prototype")
@RequestMapping("/adrelease/")
public class AdReleaseController extends BaseController {

	@Autowired
	private AdReleaseService adreleaseService;
	@Autowired
	private AdPositionService adPositionService;
	@Autowired
	private AdvertisementService advertisementService;
	@RequestMapping("listUI.html")
	public String listUI(Model model, HttpServletRequest request,Long id,String date,String code) {
		try
		{
			PageUtil page = new PageUtil();
			if(request.getParameterMap().containsKey("page")){
				page.setPageNum(Integer.valueOf(request.getParameter("page")));
				page.setPageSize(Integer.valueOf(request.getParameter("rows")));
				page.setOrderByColumn(request.getParameter("sidx"));
				page.setOrderByType(request.getParameter("sord"));
			}
			if(id!=null){
				String ids=adPositionService.findById(id).getCode();
				model.addAttribute("ids", ids);
			}
			if(code!="" && code!=null){
				model.addAttribute("ids", code);
			}
			if(date!="" && date!=null){
				model.addAttribute("dates", date);
			}
			model.addAttribute("page", page);
			return Common.BACKGROUND_PATH + "/adrelease/list";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	
	
	@RequestMapping("list.html")
	@ResponseBody
	public Object list(String gridPager,HttpServletResponse response,String id,String date) throws Exception{
		System.out.println(id+"||"+date);
		Map<String,Object> parameters = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(gridPager, Pager.class);
		// 判断是否包含自定义参数
		parameters = pager.getParameters();
		if (parameters.size() < 0) {
			parameters.put("name", null);
		}//3、判断是否是导出操作
		if(pager.getIsExport())
		{
			if(pager.getExportAllData())
			{
				//3.1、导出全部数据
				List<AdReleaseEntity> list = adreleaseService.queryListByPage(parameters);
				ExportUtils.exportAll(response, pager, list);
				return null;
			}else
			{
				//3.2、导出当前页数据
				ExportUtils.export(response, pager);
				return null;
			}
		}else
		{
		// 设置分页，page里面包含了分页信息
		Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize());
		List<HashMap<String , Object>> list =new ArrayList<>();
		//列表展示数据
		
		if(id!=null && id!=""){
			if(date!=null && date!=""){
				String enddate=date+" 23:59:59";
				list=adreleaseService.queryListByAdRelease(id,date,enddate,"");
			}else{
				/*if(parameters.get("ida")!=null & parameters.get("ida")!="" ){
					id= (String)parameters.get("ida");
				} */
				 list =adreleaseService.queryListByAdP(id);
			}
			
			
		}
		parameters.clear();
		parameters.put("isSuccess", Boolean.TRUE);
		parameters.put("nowPage", pager.getNowPage());
		parameters.put("pageSize", pager.getPageSize());
		parameters.put("pageCount", page.getPages());
		parameters.put("recordCount", page.getTotal());
		parameters.put("startRecord", page.getStartRow());
		
		parameters.put("exhibitDatas", list);
		return parameters;
	}
	}
	//添加显示
	@RequestMapping("addUI.html")
	public String addUI(Model model, HttpServletRequest request, String code) {
		
		model.addAttribute("positionCode",code);
		return Common.BACKGROUND_PATH + "/adrelease/form";
	}
	//添加
	@RequestMapping("add.html")
	@ResponseBody
	public Object add(AdReleaseEntity dictionary,String sDate,String eDate) throws ParseException
	{
		Map<String, Object> map = new HashMap<String, Object>();
		

		try
		{
			
			if(sDate!=null && sDate!=""){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date=format.parse(sDate);
				dictionary.setStartTime(date);
			}
			if(eDate!=null && eDate!=""){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date=format.parse(eDate);
				dictionary.setEndTime(date);
			}
			if( dictionary.getIsApply()==null ){
				dictionary.setIsApply("否");
				dictionary.setStatus("APPROVED_NONE");
				if(dictionary.getStatus()==null){
					dictionary.setStatus("APPROVED_NONE");
				}else if(!dictionary.getStatus().equals("APPROVED_NONE")){
					dictionary.setStatus("APPROVED_NONE");
				}
			}else if(dictionary.getIsApply().equals("否") ){
				if(dictionary.getStatus()==null){
					dictionary.setStatus("APPROVED_NONE");
				}else if(!dictionary.getStatus().equals("APPROVED_NONE")){
					dictionary.setStatus("APPROVED_NONE");
				}
			}else {
				dictionary.setStatus("APPROVED_SUCCESS");
			}
			if(dictionary.getType().equals("独占")){
				List<AdReleaseEntity> list=adreleaseService.queryListByAdPAnddate(dictionary.getPositionCode(),sDate, eDate, "");
				if(list.size()>0){
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "独占广告不能与其他广告同时间段共享广告位");
				}else{
					int count=adreleaseService.insert(dictionary);
					if(count >0 )
					{
						map.put("success", Boolean.TRUE);
						map.put("data", null);
						map.put("message", "添加成功");
					}else
					{
						map.put("success", Boolean.FALSE);
						map.put("data", null);
						map.put("message", "添加失败");
					}
				}
			}else{
				List<AdReleaseEntity> list=adreleaseService.queryListByAdPAnddate(dictionary.getPositionCode(),sDate, eDate, "独占");
				if(list.size()>0){
					System.out.println(list.get(0).getPositionCode());
					map.put("success", Boolean.FALSE);
					map.put("data", null);
					map.put("message", "您所填时间段有独占广告,不能共享广告位");
				}else{
					int count=adreleaseService.insert(dictionary);
					if(count >0 )
					{
						map.put("success", Boolean.TRUE);
						map.put("data", null);
						map.put("message", "添加成功");
					}else
					{
						map.put("success", Boolean.FALSE);
						map.put("data", null);
						map.put("message", "添加失败");
					}
				}
			}
			
			 
			
		}catch(ServiceException e)
		{
			throw new AjaxException(e);
		}
		return map;
	}
	//审核通过
			@RequestMapping("updateStatus.html")
			@ResponseBody
			public Object updateStatus(String ids){
				System.out.println(ids);
				Map<String, Object> result = new HashMap<String, Object>();
				SeriesEntity entity=new SeriesEntity();
				try
				{
					String[] seriesIds = ids.split(",");
					List<Long> list = new ArrayList<Long>();
					for (String string : seriesIds) {
						list.add(Long.valueOf(string));
					}
					int cnt = adreleaseService.updatePass(list);
					if(cnt == list.size())
					{
						result.put("success", true);
						result.put("data", null);
						result.put("message", "上线成功");
					}else
					{
						result.put("success", false);
						result.put("data", null);
						result.put("message", "上线失败");
					}
				}catch(Exception e)
				{
					throw new AjaxException(e);
				}
				return result;
			}
	//修改显示
	@RequestMapping("editUI.html")
	public String editUI(Model model, HttpServletRequest request, Long id,String code) {
		System.out.println(code);
		try
		{
			AdReleaseEntity dictionary=adreleaseService.findById(id);
			AdvertisementEntity advertisementEntity=advertisementService.findById(dictionary.getAdId().longValue());
			PageUtil page = new PageUtil();
			page.setPageNum(Integer.valueOf(request.getParameter("page")));
			page.setPageSize(Integer.valueOf(request.getParameter("rows")));
			page.setOrderByColumn(request.getParameter("sidx"));
			page.setOrderByType(request.getParameter("sord"));
			Date date =dictionary.getStartTime();
			if(date!=null){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String sdate=format.format(date);
				model.addAttribute("sdate",sdate);
			}
				date =dictionary.getEndTime();
			if(date!=null){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String edate=format.format(date);
				model.addAttribute("edate",edate);
			}
			model.addAttribute("page", page);
			model.addAttribute("adreleaseentity", dictionary);
			model.addAttribute("adNames",advertisementEntity.getTitle());
			model.addAttribute("positionCode",code);
			return Common.BACKGROUND_PATH + "/adrelease/form";
		}catch(Exception e)
		{
			throw new SystemException(e);
		}
	}
	//修改
	@RequestMapping("edit.html")
	@ResponseBody
	public Object update(AdReleaseEntity dictionaryIds,String sDate,String eDate)
	{
		System.out.println(dictionaryIds.getIsApply()+"============"+dictionaryIds.getStatus()+"========="+dictionaryIds.getType());
		Map<String, Object> map = new HashMap<String, Object>();
		if( dictionaryIds.getIsApply()==null){
			dictionaryIds.setIsApply("否");
			dictionaryIds.setStatus("APPROVED_NONE");
			if(dictionaryIds.getStatus()==null){
				dictionaryIds.setStatus("APPROVED_NONE");
			}else if(!dictionaryIds.getStatus().equals("APPROVED_NONE")){
				dictionaryIds.setStatus("APPROVED_NONE");
			}
		}else if(dictionaryIds.getIsApply().equals("否") ){
			if(dictionaryIds.getStatus()==null){
				dictionaryIds.setStatus("APPROVED_NONE");
			}else if(!dictionaryIds.getStatus().equals("APPROVED_NONE")){
				dictionaryIds.setStatus("APPROVED_NONE");
			}
		}else {
			dictionaryIds.setStatus("APPROVED_SUCCESS");
		}
		
		try
		 {  	SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if(sDate!=null && sDate!=""){
				Date date=format.parse(sDate);
				dictionaryIds.setStartTime(date);
				}
				if(eDate!=null && eDate!=""){
					Date date=format.parse(eDate);
					dictionaryIds.setEndTime(date);
				}
				
				if(dictionaryIds.getType().equals("独占")){
					List<AdReleaseEntity> list=adreleaseService.queryListByAdPAnddate(dictionaryIds.getPositionCode(),sDate, eDate, "");
					if(list.size()>1){
						map.put("success", Boolean.FALSE);
						map.put("data", null);
						map.put("message", "独占广告不能与其他广告同时间段共享广告位");
					}else{
						int count=adreleaseService.update(dictionaryIds);;
						if(count >0 )
						{
							map.put("success", Boolean.TRUE);
							map.put("data", null);
							map.put("message", "保存成功");
						}else
						{
							map.put("success", Boolean.FALSE);
							map.put("data", null);
							map.put("message", "保存失败");
						}
					}
				}else{
					List<AdReleaseEntity> list=adreleaseService.queryListByAdPAnddate(dictionaryIds.getPositionCode(),sDate, eDate, "独占");
					if(list.size()>1){
						System.out.println(list.get(0).getPositionCode());
						map.put("success", Boolean.FALSE);
						map.put("data", null);
						map.put("message", "您所填时间段有独占广告,不能共享广告位");
					}else{
						int count=adreleaseService.update(dictionaryIds);;
						if(count >0 )
						{
							map.put("success", Boolean.TRUE);
							map.put("data", null);
							map.put("message", "保存成功");
						}else
						{
							map.put("success", Boolean.FALSE);
							map.put("data", null);
							map.put("message", "保存失败");
						}
					}
				}
		}catch(Exception e)
		{
			throw new AjaxException(e);
		}
		return map;
	}
	
	//删除
	@RequestMapping("deleteBatch.html")
	@ResponseBody
	public Object deleteBatch(String ids) {
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			String[] seriesIds = ids.split(",");
			List<Long> list = new ArrayList<Long>();
			for (String string : seriesIds) {
				list.add(Long.valueOf(string));
			}
			int cnt = adreleaseService.deleteBatchById(list);
			System.out.println(cnt);
			if(cnt == list.size())
			{
				result.put("success", true);
				result.put("data", null);
				result.put("message", "删除成功");
			}else
			{
				result.put("success", false);
				result.put("data", null);
				result.put("message", "删除失败");
			}
		}catch(Exception e)
		{
			throw new AjaxException(e);
		}
		return result;
	}
	
	@RequestMapping("resources.html")
	public String resources(Model model,String code) {
		System.out.println(code+"=================");
		int count=advertisementService.querycount("");
		PageUtil pageUtil =new PageUtil();
		pageUtil.setPageNum(0);
		pageUtil.setPageSize(15);
		List<HashMap<String,Object>> list=advertisementService.queryAd(pageUtil, "",code);
		if(list.size()>0){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<String> datelist=new ArrayList<String>();
			for(int i=0;i<list.size();i++){
				String edate=format.format(list.get(i).get("end_date"));
				datelist.add(edate);
			}
			model.addAttribute("datelist",datelist);
		}
		model.addAttribute("videoResource_list",list);
		int totalPageCount;
		if(count>15 ){
			totalPageCount=count/15;
			 if(count%15==0){
				 model.addAttribute("totalPageCount", totalPageCount);
				  
				}else{
					model.addAttribute("totalPageCount", totalPageCount+1);}
		}else{
			totalPageCount=0;
			model.addAttribute("totalPageCount", totalPageCount);
		}
		
		System.out.println("广告数："+count);
		return Common.BACKGROUND_PATH + "/adrelease/resources";
	}
 
	@RequestMapping(value="/searchPage.html", method={RequestMethod.GET,RequestMethod.POST})
	public String searchPage(Model model, String pSize,String pageNo,String sort,String code){
		PageUtil pageUtil =new PageUtil();
		int no=Integer.parseInt(pageNo)-1;
		pageUtil.setPageNum(no*Integer.parseInt(pSize));
		pageUtil.setPageSize(Integer.parseInt(pSize));
		System.out.println(sort);
		int totalPageCount;
		int count=advertisementService.querycount(sort);
		if(count>15 ){
			totalPageCount=count/15;
			 if(count%15==0){
				 model.addAttribute("totalPageCount", totalPageCount);
				  
				}else{
					model.addAttribute("totalPageCount", totalPageCount+1);}
		}else{
			totalPageCount=0;
			model.addAttribute("totalPageCount", totalPageCount);
		}
		if(sort==null){
			sort="";
		}
		
		List<HashMap<String, Object>> list=advertisementService.queryAd(pageUtil, sort,code);
		if(list.size()>0){
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<String> datelist=new ArrayList<String>();
			for(int i=0;i<list.size();i++){
				String edate=format.format(list.get(i).get("end_date"));
				datelist.add(edate);
			}
			model.addAttribute("datelist",datelist);
		}
		model.addAttribute("videoResource_list", list);
		return Common.BACKGROUND_PATH+"/adrelease/resourceslist";
	}
}
